package com.ak.framework.aspectj;

import com.ak.common.annotation.DataSource;
import com.ak.common.config.Global;
import com.ak.common.utils.StringUtils;
import com.ak.framework.datasource.DataSourceBeanBuilder;
import com.ak.framework.datasource.DataSourceHolder;
import com.ak.framework.util.ShiroUtils;
import com.ak.platform.domain.system.SysDatasource;
import com.ak.platform.service.system.ISysDatasourceService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 多数据源切换处理
 *
 * @author Vean
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {

    @Resource
    private ISysDatasourceService dataSourceService;

    @Pointcut("@annotation(com.ak.common.annotation.DataSource)")
    public void dsPointCut() {}

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();

        Method method = signature.getMethod();

        DataSource dataSource = method.getAnnotation(DataSource.class);
        // 跳过默认数据源
        if (StringUtils.isNotNull(dataSource) && null != ShiroUtils.getSysUser() && !Global.DEFAULT_TENANT_CODE.equals(ShiroUtils.getSysUser().getTenantCode())) {
            SysDatasource _dataSource_ = this.dataSourceService.queryByTenantAppAndDatabaseType(ShiroUtils.getSysUser().getTenantCode(), dataSource.appCode(), dataSource.databaseFlag());
            if (_dataSource_ != null) {
                DataSourceBeanBuilder builder = new DataSourceBeanBuilder(_dataSource_);
                DataSourceHolder.setDataSource(builder);
            } else {
                throw new RuntimeException("获取数据源信息异常，请检查租户 [" + ShiroUtils.getSysUser().getTenantCode() +"] 的数据源配置");
            }
        }

        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DataSourceHolder.clearDataSource();
        }
    }
}
